package com.vpclub;

import com.vpclub.bean.Blue;
import com.vpclub.bean.Person;
import com.vpclub.config.MainConfig2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.Environment;

import java.util.stream.Stream;

/**
 * @author : leimingchao
 * @Description:
 * @date Date : 2021年06月12日 20:50
 */
public class IOCTest2 {

    private ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);

    @Test
    public void test01() {
        System.out.println("ioc容器创建完成。。。。。");
        // Stream.of(applicationContext.getBeanDefinitionNames()).forEach(System.out::println);
        Object bean = applicationContext.getBean("person");
        Object bean2 = applicationContext.getBean("person");
        System.out.println(bean == bean2);

    }

    @Test
    public void test02() {
        Stream.of(applicationContext.getBeanNamesForType(Person.class)).forEach(System.out::println);

        Environment environment = applicationContext.getEnvironment();
        // 动态获取环境变量的值，获取操作系统的名字
        String property = environment.getProperty("os.name");
        System.out.println(property);

        applicationContext.getBeansOfType(Person.class).forEach((key,value)->{
            System.out.println(key + "------>" +value);
        });
        System.out.println("--------------------------------------");
        Stream.of(applicationContext.getBeanDefinitionNames()).forEach(System.out::println);
    }

    @Test
    public void testImport() {
        printBeans(applicationContext);
        Blue bean = applicationContext.getBean(Blue.class);
        System.out.println(bean);
        //工厂bean获取的是调用getObject创建的对象
        Object bean2 = applicationContext.getBean("colorFactoryBean");
        Object bean3 = applicationContext.getBean("colorFactoryBean");
        System.out.println("bean的类型：" + bean2.getClass());
        System.out.println(bean2 == bean3);
        Object bean4 = applicationContext.getBean("&colorFactoryBean");
        System.out.println(bean4.getClass());

        // MyImportBeanDefinitionRegistrar2 myImportBeanDefinitionRegistrar2 = applicationContext.getBean(MyImportBeanDefinitionRegistrar2.class);
        // System.out.println(myImportBeanDefinitionRegistrar2);

    }

    private void printBeans(ApplicationContext applicationContext) {
        Stream.of(applicationContext.getBeanDefinitionNames()).forEach(System.out::println);
    }
}
